#!/bin/bash

PATH=$PATH

SSHFSCMD="sshfs"
SSHFSOPTION="-o follow_symlinks"
BASEPATHKEYWORD="SSHFS"
LOCALBASEPATH="${HOME}/${BASEPATHKEYWORD}"
LOCALHOST=`hostname -s`

CHKPARA=0

if [ -n "$1" ]; then
    SiteCode="$1"
    shift
else
    CHKPARA=1
fi

if [ -n "$1" ]; then
    ACCOUNT="$1"
    shift
else
    CHKPARA=1
fi

if [ -n "$1" ]; then
    REMOTEPATH="$1"
    shift
fi

if [[ ${LOCALHOST} = ${SiteCode} ]]; then
    echo "Error : Do not need to mount directory in local machine(${SiteCode}) via sshfs."
    echo ""
    CHKPARA=1
fi

if [ $CHKPARA -eq 1 ]; then
    echo "Usage : $0 SiteCode Account [RemotePath]"
    echo "Example : $0 SSHServerName RemoteServerAccountName"
    echo "Example : $0 SSHServerName RemoteServerAccountName /home/RemoteServerAccountName"
    echo "SiteCode : SSHServerName SSHServerName1 SSHServerName2"
    echo "Account : Your account name in remote host"
    echo ""
    echo "SSHFS Mount Status"
    df -h | grep ${BASEPATHKEYWORD}
    exit 1
else
    ### Check SSH server
    SITE=${SiteCode}
    NFSSTATUS=`echo -en "o ${SITE} 22\nsend escape\nquit\nclose\n" | telnet 2>/dev/null | grep "]" | wc -l`
    if [ $NFSSTATUS -ne 1 ]; then
        echo "Could not connect to SSH server ${SITE}."
        exit 1
    else
        echo "SSH server ${SITE} is alive."
    fi

    ### Prepare for mount sshfs
    REMOTEHOST=${SiteCode}
    REMOTEACCOUNT=${ACCOUNT}
    LOCALHOSTPATH=${SiteCode}
    if [ -z ${REMOTEPATH} ]; then
        REMOTEPATH="/home/${REMOTEACCOUNT}"
    fi

    echo "Remote Host : ${REMOTEHOST}"
    echo "Remote Account : ${REMOTEACCOUNT}"
    echo "Remote Path : ${REMOTEPATH}"
    echo "Local Host : ${LOCALHOST}"
    echo "Mount Path : ${LOCALBASEPATH}/${LOCALHOSTPATH}"
    echo ""

    if [ ! -d ${LOCALBASEPATH}/${LOCALHOSTPATH} ]; then
        echo "Prepare the mount path : ${LOCALBASEPATH}/${LOCALHOSTPATH}"
        mkdir -p ${LOCALBASEPATH}/${LOCALHOSTPATH}
        echo "Mount Command : ${SSHFSCMD} ${REMOTEACCOUNT}@${REMOTEHOST}:${REMOTEPATH} ${LOCALBASEPATH}/${LOCALHOSTPATH} ${SSHFSOPTION}"
        ${SSHFSCMD} ${REMOTEACCOUNT}@${REMOTEHOST}:${REMOTEPATH} ${LOCALBASEPATH}/${LOCALHOSTPATH} ${SSHFSOPTION}
    else
        echo "Error : The mount path ${LOCALBASEPATH}/${LOCALHOSTPATH} had been existed."
    fi

    echo ""
    echo "SSHFS Mount Status"
    df -h | grep ${BASEPATHKEYWORD} | grep ${REMOTEHOST}
fi
